package com.jason.game.online.widget

import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat.getDrawable
import com.cby.library.common.ext.setBackgroundKeepingPadding
import com.cby.library.common.ext.setFontColor
import com.cby.library.tool.util.ScreenUtils
import com.jason.game.online.R
import com.jason.game.online.utils.DataConvertUtils
import java.lang.StringBuilder

/**
 * 游戏分类
 */
class GameCategoryItem : LinearLayout {
    private lateinit var mTextView: TextView
    private lateinit var mScoreTextView: TextView

    constructor(context: Context) : super(context) {
        init(context, null)
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        init(context, attrs)
    }

    private fun init(context: Context, attrs: AttributeSet?) {
        orientation = HORIZONTAL
        mTextView = TextView(context)
        mTextView.textSize = FONT_SIZE.toFloat()
        mTextView.setFontColor(R.color.font_main_gray)
        addView(mTextView)
        mScoreTextView = addScoreView()
        val scoreLayoutParams = LayoutParams(
            ScreenUtils.dip2px(context, 36f),
            ScreenUtils.dip2px(context, 14f)
        )
        mScoreTextView.includeFontPadding = false
        scoreLayoutParams.leftMargin = ScreenUtils.dip2px(context, 6f)
        scoreLayoutParams.rightMargin = ScreenUtils.dip2px(context, 6f)
        mScoreTextView.gravity = Gravity.CENTER
        mScoreTextView.visibility = GONE
        addView(mScoreTextView, scoreLayoutParams)
    }

    /**
     * 设置分类数据
     * @param category
     * @param num
     */
    fun setData(category: String?, num: Int) {
        val sb = StringBuilder(category ?: "")
        sb.append(" | ")
        sb.append(DataConvertUtils.convertHits(num.toString()))
        mTextView.text = sb.toString()
    }

    private fun addScoreView(): TextView {
        val scoreTextView = TextView(context)
        scoreTextView.textSize = FONT_SIZE.toFloat()
        getDrawable(context, R.drawable.bg_game_score)?.let {
            scoreTextView.setBackgroundKeepingPadding(
                it
            )
        }
        scoreTextView.setFontColor(R.color.font_game_item_score)
        return scoreTextView
    }

    /**
     * 设置数据
     * @param category 分类名称
     * @param num 多少人玩
     * @param score 分数
     */
    fun setData(category: String?, num: Int, score: Double) {
        setData(category, num)
        if (score < SCORE_LEVEL) {
            mScoreTextView.visibility = GONE
        } else {
            mScoreTextView.visibility = VISIBLE
            mScoreTextView.text = "${score}分"
        }
    }

    companion object {
        private const val FONT_SIZE = 11
        private const val SCORE_LEVEL = 5
    }
}